<template>
    <section class="">
        <el-form :inline="true" :model="formSearch" class="form_inline main_center" label-width="90px">
            <!-- <el-form-item label="功能名称" size="small">
                <el-input v-model="formSearch.name" placeholder="请输入功能名称"></el-input>
            </el-form-item> -->
            <el-form-item>
                <el-button size="small" @click="getlist">查 询</el-button>
                <el-button size="small" @click="addpoint">新 增</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="tableData" stripe style="width: 100%">
            <el-table-column prop="name" label="功能名称">
            </el-table-column>
            <el-table-column prop="sn" label="功能唯一标识">
            </el-table-column>
            <el-table-column label="数据类型">
                <template slot-scope="scope">
                    {{scope.row.valueType =="bool"?"布尔类型":scope.row.valueType =="real"?"数字类型":scope.row.valueType
                    =="str"?"字符串":'--'}}
                </template>
            </el-table-column>
            <!-- <el-table-column prop="pointRef" label="功能地址"> -->
            </el-table-column>
            <el-table-column prop="" label="是否只读">
                <template slot-scope="scope">
                    {{scope.row.readOnly ==1?"是":scope.row.readOnly ==0?"否":''}}
                </template>
            </el-table-column>
            <el-table-column prop="unit" label="单位">
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button v-if="" type="text" size="small " @click="xiugaiorxq(scope.row,2)">编辑</el-button>
                    <el-button size="small " type="text" @click="deleInfor(scope.row.id)">删除</el-button>
                    <el-button size="small" type="text" @click="xiugaiorxq(scope.row,3)">详情</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 3.2 底部分页      -->
        <paging @changePage=handleCurrentPage :get-total='total'></paging>

        <el-dialog :title="addorupdata==1?'新增':addorupdata==2?'修改':'详情'" width="25%" :visible.sync="addFormVisible"
            @closed='closeadd' :close-on-click-modal="false">
            <el-form class="_form" label-position="top" :model="addForm" label-width="135px" ref="addform"
                :disabled="disabled">
                <el-form-item label="功能唯一标识：" size="small" prop="sn"
                    :rules="{ required: true, message: '该项不能为空', trigger: 'change' }">
                    <el-input :disabled="addorupdata==2?true:false" class="input100p" v-model="addForm.sn"></el-input>
                </el-form-item>
                <el-form-item label="功能名称：" size="small" prop="name"
                    :rules="{ required: true, message: '该项不能为空', trigger: 'change' }">
                    <el-input v-model="addForm.name"></el-input>
                </el-form-item>
                <el-form-item label="数据类型：" size="small" prop="valueType"
                    :rules="{ required: true, message: '该项不能为空', trigger: 'change' }">
                    <el-select v-model="addForm.valueType" @change="valueTypechange" placeholder="请选择数据类型">
                        <el-option label="布尔类型" value="bool"></el-option>
                        <el-option label="数字类型" value="real"></el-option>
                        <el-option label="字符串" value="str"></el-option>
                        <el-option label="float(单精度浮点型)" value="float"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="布尔值：" v-if="addForm.valueType == 'bool'" size="small">
                    <div class="booldata" style="display: flex;">
                        <el-input class="input200" placeholder="" v-model="addForm.dataTypeValue.trueText"></el-input>
                        <span class="boolspan">~</span>
                        <el-select v-model="addForm.dataTypeValue.trueValue" placeholder="请选择">
                            <el-option label="ture" value="ture"></el-option>
                            <el-option label="0" value="0"></el-option>
                        </el-select>
                        <!-- <el-input class="input200" placeholder="" v-model="addForm.dataTypeValue.trueValue"></el-input> -->
                    </div>
                    <div style="display: flex;">

                        <el-input class="input200" placeholder="" v-model="addForm.dataTypeValue.falseText"></el-input>
                        <span class="boolspan">~</span>
                        <!-- <el-input class="input200" placeholder="" v-model="addForm.dataTypeValue.falseValue"></el-input> -->
                        <el-select v-model="addForm.dataTypeValue.falseValue" placeholder="请选择">
                            <el-option label="false" value="false"></el-option>
                            <el-option label="1" value="1"></el-option>
                        </el-select>
                    </div>
                </el-form-item>
                <el-form-item label="精度：" v-if="addForm.valueType == 'float'" size="small">
                    <el-input v-model="addForm.dataTypeValue.precision"></el-input>
                </el-form-item>
                <el-form-item label="单位：" size="small">
                    <!-- <el-input v-model="addForm.unit"></el-input> -->
                    <el-select v-model="addForm.unit" placeholder="请选择单位">
                        <el-option-group v-for="group in unitdatagroup" :key="group.label" :label="group.label">
                            <el-option v-for="item in group.options" :label="item.name" :value="item.name"
                                :key="item.id">
                            </el-option>
                        </el-option-group>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否只读：" size="small" prop="readOnly"
                    :rules="{ required: true, message: '该项不能为空', trigger: 'change' }">
                    <el-radio-group v-model="addForm.readOnly">
                        <el-radio :label="true">是</el-radio>
                        <el-radio :label="false">否</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="描述：" size="small">
                    <el-input type="textarea" autosize v-model="addForm.description"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="closeadd">取消</el-button>
                <el-button v-if="addorupdata!=3" type="primary" @click.native="addlist">提交</el-button>
            </div>
        </el-dialog>
    </section>
</template>

<script>
    import paging from "../paging"
    import { devicefunctionlist, devicefunctionupdate, devicefunctiondelete, devicefunctionadd, unitlist } from '../../url/api'
    export default {
        props: ['type'],
        data() {
            return {
                unitdata: [],
                tableData: [],
                formSearch: {},
                ProDData: {},
                addorupdata: 1,
                total: 0,//数据总数
                addForm: {
                    deviceId: '',
                    deviceType: '',
                    name: '',
                    pointRef: '',
                    readOnly: 1,
                    sn: '',
                    unit: '',
                    valueType: '',
                    description: '',
                    dataTypeValue: {}
                },
                addFormVisible: false,
                addorupdata: 1,
                disabled: false,
                rowid: '',
                unitdatagroup: [],
                devicetype:'',
            }
        },
        methods: {
            handleCurrentPage(val) {//页码改变
                this.formSearch.current = val
                //   this.getlist()
            },
            valueTypechange(data) {
                if (data == 'bool') {
                    let dataTypeValue = {
                        trueText: '',
                        trueValue: '',
                        falseText: '',
                        falseValue: ''
                    }
                    this.addForm.dataTypeValue = dataTypeValue;
                    //console.log(this.addForm);
                }
                if (data == 'float') {
                    let dataTypeValue = {
                        precision: '',
                    }
                    this.addForm.dataTypeValue = dataTypeValue;
                    //console.log(this.addForm);
                }
            },
            deleInfor(id) {
                let arrId = []
                if (id) {
                    arrId.push(id)
                }
                // else {//批量删除
                //     if (this.deleBatch.length != 0) {
                //         this.deleBatch.filter((item) => {
                //             arrId.push(item.id)
                //             return item
                //         })
                //     } else {
                //         this.$message('请勾选要删除的数据！')
                //         return
                //     }
                // }
                this.$confirm("确定删除吗？", '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    devicefunctiondelete(arrId).then((res) => {
                        //console.log("删除", res)
                        if (res.data.ok) {
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            this.getlist()
                        } else {
                            this.$message('删除失败')
                        }
                    })

                }).catch(() => {

                });
            },
            xiugaiorxq(row, index) {
                this.addorupdata = index
                if (index == 3) {
                    this.disabled = true
                }
                this.rowid = row.id
                this.addForm = {
                    deviceId: this.ProDData.id,
                    deviceType: this.devicetype,
                    name: row.name,
                    // pointRef: row.pointRef,
                    readOnly: row.readOnly, // ==true?1:row.readOnly==false?0:'',
                    sn: row.sn,
                    unit: row.unit,
                    valueType: row.valueType,
                    description: row.description,
                    dataTypeValue: row.dataTypeValue
                };
                if(row.dataTypeValue!=''){
                    this.addForm.dataTypeValue = JSON.parse(row.dataTypeValue);
                }
                    this.addFormVisible = true;
            },
            addlist() {
                //console.log("this.addF", this.addForm)
                this.$refs.addform.validate((valid) => {
                    // //console.log("valid", valid)
                    if (valid) {
                        this.addForm.deviceId = this.ProDData.id;
                        this.addForm.deviceType = this.devicetype;
                        if (this.addForm.valueType == "bool") {
                            this.addForm.dataTypeValue = JSON.stringify(this.addForm.dataTypeValue).toString();
                        }
                        JSON.stringify(this.addForm.dataTypeValue)
                        if (JSON.stringify(this.addForm.dataTypeValue) == "{}") {
                            delete this.addForm.dataTypeValue
                        }
                        // delete this.addForm.xqId
                        this.$confirm("确定执行此操作吗？", '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            // this.adddialog = false
                            //console.log(this.addForm)
                            if (this.addorupdata == 1) {
                                devicefunctionadd(this.addForm).then((res) => {
                                    //console.log("新增", res)
                                    if (res.data.ok) {
                                        this.$message({
                                            message: '添加成功',
                                            type: 'success'
                                        });
                                        this.getlist()
                                        this.addorupdata == 1
                                    } else {
                                        this.$message('添加失败')
                                    }
                                    this.closeadd()
                                })
                            } else if (this.addorupdata == 2) {
                                this.addForm.id = this.rowid
                                // debugger
                                devicefunctionupdate(this.addForm).then((res) => {
                                    if (res.data.ok) {
                                        this.$message({
                                            message: '修改成功',
                                            type: 'success'
                                        });
                                        this.getlist()
                                        this.addorupdata == 1
                                    } else {
                                        this.$message('修改失败')
                                    }
                                    this.closeadd()
                                })
                            }
                            this.adddialog = false

                        })

                    } else {
                        //console.log('error submit!!');
                        return false;
                    }
                });
            },
            closeadd() {
                this.addForm = {
                    deviceId: this.ProDData.id,
                    deviceType: this.devicetype,
                    name: '',
                    pointRef: '',
                    readOnly: 1,
                    sn: '',
                    unit: '',
                    valueType: '',
                    dataTypeValue: {}
                },
                    this.$refs.addform.resetFields();
                this.addorupdata = 1
                this.addFormVisible = false;
                this.disabled = false
            },
            addpoint() {
                this.addFormVisible = true;
                this.addorupdata = 1;
            },
            getUnitList() {
                unitlist().then((res) => {//
                    //console.log(res)
                    if (res.data.ok) {
                        this.unitdata = res.data.data;
                        // //console.log(res.data.data);
                    }
                    if (this.unitdata.length > 0) {
                        let data = []
                        this.unitdata.forEach((item) => {
                            // debugger
                            data.push(item.label);
                        });
                        // console.log(data);
                        this.setUnitListgroup(data);
                    }
                })
            },
            //封装单位组
            setUnitListgroup(unitdata) {
                let obj = {}
                var newArr = []
                for (let i = 0; i < unitdata.length; i++) {
                    if (!obj[unitdata[i]]) {
                        obj[unitdata[i]] = 1
                        newArr.push(unitdata[i])
                    }
                }
                // console.log(newArr, "AAAAAAAAAAAAAAA");
                let options = []
                newArr.forEach((val) => {
                    let lable = {
                        label: val,
                        options: []
                    }
                    options.push(lable);
                })
                this.unitdata.forEach((item) => {
                    // debugger
                    options.forEach((elem) => {
                        if (item.label == elem.label) {
                            elem.options.push(item);
                        }
                    })
                });
                // console.log("终结：", options);
                this.unitdatagroup = options
            },
            getlist() {
                // console.log(this.devicetype,this.type,"QQQQQQQQ");
                this.devicetype = this.type;
                if(this.devicetype=="device"){
                    this.ProDData = JSON.parse(sessionStorage.getItem('deviceData'))
                }else if(this.devicetype=="product"){
                    this.ProDData = JSON.parse(sessionStorage.getItem('productData'))
                }
                
                let params = {
                    deviceType: this.devicetype,
                    deviceId: this.ProDData.id,
                }
                
                devicefunctionlist(params).then((res) => {//
                    //console.log(res)
                    if (res.data.ok) {
                        this.tableData = res.data.data.records;
                        //console.log(res.data.data);
                        this.total = res.data.data.total * 1
                    }
                })

                // //console.log("AAAAAAAAAAAAAAA",this);
            }
        },
        watch: {
            type: function (data) {
                this.devicetype = data;
                console.log(this.devicetype, "AAAAAAAAA"); //data便是pcData
                // this.getlist();
            }
        },
        mounted() {
            this.getlist();
            this.getUnitList()
        },
        components: {
            paging
        }
    }
</script>
<style scoped>
    .input200 {
        width: 200px;
    }

    .boolspan {
        width: 40px;
        text-align: center;
    }

    ._form /deep/ .el-input__inner {
        max-width: 100%;
    }

    ._form /deep/ .el-select {
        display: block;
    }
</style>